<template>
  <div style="margin: 10px 0">
    <!-- SKU -->
    <el-card class="box-card" style="min-height: 80vh" shadow="hover">
      <div slot="header" class="clearfix">
        <!-- 头部左侧 -->
        <div class="media-display">
          <el-link :underline="false" style="font-size: 20px">添加产品</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link :underline="false" style="font-size: 20px">SKU(商品变种)</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link :underline="false" style="font-size: 20px">第{{ index }}个变种</el-link>
          <el-divider direction="vertical"></el-divider>

          <!--          <el-divider direction="vertical"></el-divider>
                    {{ spu.attributeList }}
                    <el-divider direction="vertical"></el-divider>
                    {{ spu.dbAttributeList }}-->
          {{ sku.productSpecs }}

        </div>
      </div>
      <!-- 内容 -->
      <div class="text" style="width: 60vw">

        <el-form :model="sku" ref="sku" label-width="100px" class="demo-sku" :disabled="skuDisabledList[index - 1]">
          <el-form-item label="产品 ID" prop="productId" class="sku-input">
            <el-input  v-model="spu.productId" :readonly="true"></el-input>
            <div class="el-form-item__error info">
              该项只读，信息由spu生成
            </div>
          </el-form-item>


          <el-form-item label="选择规格"
                        style="margin-bottom: 5px"
                        :key="index"
                        prop="productSpecs"
                        :rules="rules.attribute">
            <!-- 颜色： -->
            <div v-for="(item,index) in spu.attributeList">
              <el-link :underline="false" style="font-size: 20px">{{ item.key }}:</el-link>
              <el-radio-group v-model="sku.productSpecs[item.key]"
                              size="small" style="margin: 0 5px">
                <!-- "墨羽", "银迹" -->
                <el-radio-button
                  :label="item"
                  v-for="(item, index) in item.value" :key="index">
                  {{ item }}
                </el-radio-button>
              </el-radio-group>
            </div>

          </el-form-item>

          <el-form-item label="规格 ID" prop="productId" style="margin-top: 20px" class="sku-input">
            <el-input v-model="sku.specsId" :readonly="true"></el-input>
            <div class="el-form-item__error info">
              该项只读，信息由选择生成
            </div>
          </el-form-item>

          <el-form-item label="产品规格信息" prop="productSpecs" class="sku-input">
            <el-input :value="sku.productSpecs | productSpecsFilter" :readonly="true"></el-input>
            <div class="el-form-item__error info">
              该项只读，信息由选择生成
            </div>
          </el-form-item>

          <!-- upload -->
          <el-form-item label="规格图片">
            <specsUpload :limit="1" :multiple="false" formDataName="specsImg" :index="index - 1" ref="specsImgUpload"></specsUpload>
          </el-form-item>

          <el-form-item label="规格价格" prop="price">
            <el-input-number v-model="sku.price" :precision="2" :step="1" :min="1" :max="9999"></el-input-number>
          </el-form-item>
          <el-form-item label="规格库存" prop="specsStock">
            <el-input-number v-model="sku.specsStock"  :step="1" :min="1" :max="9999"></el-input-number>
          </el-form-item>

          <el-form-item label="规格状态" prop="state">
            <el-switch
              v-model="sku.state"
              :active-value="1"
              :inactive-value="0"
              active-text="正常"
              inactive-text="锁定">
            </el-switch>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="lockForm()">锁定信息</el-button>
            <el-button type="primary" @click="submitForm('sku')">测试上传</el-button>

            <el-button @click="resetForm('sku')">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button @click="unlockForm()" :disabled="!skuDisabledList[index - 1]" type="warning" size="small" plain>解锁sku，重新输入</el-button>

      </div>
    </el-card>
  </div>
</template>


<script>
  import specsUpload from '@/views/product/add/sku/specsUpload'
  import {mapGetters,mapMutations} from 'vuex'
  import { skuRules } from '@/rules/product'

  export default {
    name: "sku",
    props: ['index'],
    components: { specsUpload },
    data() {
      let validateAttributes = (rule, value, callback) => {
        //console.log(Object.values(value))
        let values = Object.values(value)
        if (!values.includes("")) {// sku属性值不能为空
          //console.log("skuList =",this.skuList)
          this.skuList.forEach((item, index)=>{// 判断vuex中的sku属性是否有重复的
            //console.log(values)
            //console.log(Object.values(item.productSpecs))
            if (values.sort().toString() === Object.values(item.productSpecs).sort().toString()){
              callback(new Error('规格信息重复！'));
            }
          })
          callback();
        }
        else {
          callback(new Error('还未选择规格！'));
        }
      };
      return {
        /* SKU */
        rules: {
          attribute: [
            { validator: validateAttributes, trigger: 'change' },
          ],
        },

        sku: {
          productId: '',// 产品id
          specsId: '',// 规格id
          productSpecs: {},// 产品规格信息
          price: 1.00,// 价格
          specsStock: '',// 库存
          state: 1,// 状态
        },
      };
    },
    methods: {
      unlockForm(){
        this.$store.commit('product/REMOVE_SKU_LIST', this.index - 1)
        this.$store.commit('product/UPDATE_SKU_DISABLED_LIST', {index: this.index - 1,value: false})
      },
      lockForm() {
        console.log(this.sku)

        let sku = this.validate()
        let specsImgUpload = this.$refs.specsImgUpload.validate()
        if (sku && specsImgUpload) {
          this.$refs.specsImgUpload.submitUpload()// 将规格图信息加入vuex
          /*this.sku.productSpecs = "'" + this.sku.productSpecs + "'"*/
          //this.sku.productSpecs = JSON.stringify(this.sku.productSpecs)

          // 向skuList添加sku信息
          this.$store.commit('product/SET_SKU_LIST', this.sku)
          // 更新skuDisabledList，锁定该sku表单
          this.$store.commit('product/UPDATE_SKU_DISABLED_LIST', {index: this.index - 1,value: true})

          //this.$notify.success({title: '成功',message: 'spu信息正确，锁定信息！', duration: 1500});
          return true
        } else {
          this.$notify.warning({title: '错误',message: '属性信息有误，请检查！', duration: 1500});
          return false;
        }
      },
      // 验证是否合法
      validate(){
        let flag = true;
        this.$refs['sku'].validate((valid) => {
          flag =  valid;
        });
        return flag;
      },
      submitForm() {
        console.log(this.sku)
        this.$refs['sku'].validate((valid) => {
          if (valid) {
            this.$refs.specsImgUpload.submitUpload()// 将规格图信息加入vuex

            this.$store.commit('product/SET_SKU_LIST', this.sku)
            this.$store.commit('product/UPDATE_SKU_DISABLED_LIST', {index: this.index - 1,value: true})

            this.$notify.success({title: '成功',message: 'spu信息正确，锁定信息！', duration: 1500});
          } else {
            this.$notify.warning({title: '错误',message: '属性信息有误，请检查！', duration: 1500});
            return false;
          }
        });
      },
      init(){
        this.sku.productId = this.spu.productId
        this.spu.attributeList.forEach((item) => {
          this.$set(this.sku.productSpecs, item.key, '')
        })
        //this.sku.productSpecs = "\"" + this.sku.productSpecs + "\""

        //console.log("sku init",this.sku.productSpecs)
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
    },
    computed: {
      //使用mapState自动生成计算属性
      ...mapGetters(['spu','skuList','skuDisabledList']),//数组写法
    },
    watch: {
      "sku.productSpecs": {
        deep: true,
        handler: function (newValue, oldValue) {
          //console.log(newValue, oldValue)
          let specs = "";
          Object.values(this.sku.productSpecs).forEach(value =>{
            specs += "-" + value
            //console.log(specs) // -8GB+128GB
          })

          this.sku.specsId = this.spu.productId + specs
        }
      },
    },
    filters: {
      productSpecsFilter(value){
/*        console.log(JSON.stringify(value))
        value = value.substring(1, value.length - 1)
        console.log(value)*/
        return JSON.stringify(value);
      }
    },
    beforeMount (){//初始化数据
      this.init()
    },
    mounted(){
    },
  }
</script>

<style scoped>
  .sku-input{
    width: 50%
  }
  .info{
    color: #909399;
  }

  .clearfix{
    display: flex;
    align-items: center;
  }
  .text {
    font-size: 14px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
</style>
